package com.fr71.project.dm.utils.pay_utils;

import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.CloseOrderRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.partnerpayments.nativepay.model.Transaction;

public class WxPayUtil {

    //商户ID
    private static final String MID = "1630045615";

    //私钥
    private static final String PK = "-----BEGIN PRIVATE KEY-----\n" +
            "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDd3WhLomYL9CmC\n" +
            "vXh+JEd2bdfsPz0MGkoqxIMwaWPaj1xW8YmtIc86W9L9rtc165raCsVVwVSDvDsK\n" +
            "2FWbmcM8CpVgwS9ffHfaitEXn24chmqW1rpdspOHLVJH8LfBrBEyQIe8SKfsnTrb\n" +
            "Wk9Q2H3tf904adzmaT8T8c2Bs8Lqw8xRcbZOJuvz+283SlnOEWIkymS63uMfVFir\n" +
            "4c9IaMvAiSFpfvwbpu+sVKoTyX2uwZ1gpBEV6fTRyxM4vihGGiWh9O4DKMmJHg9J\n" +
            "OPgRWslMYGGw0fvt8NShpphiFp+2WiuPnJ1oGyVouMODRn/XwXDP/dcXMW0qNrgB\n" +
            "/M4Z+x7/AgMBAAECggEBAIyZj0q/M+RHazcLU5y86PzIR5nTyaAt2OqZdnnrj/gl\n" +
            "+eKvVwx87JKTNnbFomTtVkjvonbh+ekyFEifKEFfhDY8jsWuJ5NfkaTRbAiIZIN3\n" +
            "O30zvw855/w2YHputkTqAkvSUTKk6KYuTepMpQ8a41LrQQpLLE5oTC0bg5y6ir+y\n" +
            "/sga9naDNqwYl8V2yZoytV5IBeBChEvOi4wX8e15QpaFej0DZ2Bas3DoyaNNILsB\n" +
            "dniSnryg6zsxY5Y4UiO6fIqv2sTM2isvLmFEBn0m2JVVN51pO3CCCVU8vxgS4JHm\n" +
            "ig/c5c2h8ddem6mZxFA0qrz8E4Tx70uQ0lMVjujXzyECgYEA/l7U6HiGlEoHIb5b\n" +
            "EWMOgOI3oYvH5KpjDyJ5/Se+RY46Z9v2hAx3JvalmusoYch2yYgluX+ySgOyGQAT\n" +
            "u8ruXr9SOfHncZoklLw9eh0YnrhlAk4r2mPchbYKEuTij/dyplnc2TKeTb7sr8ld\n" +
            "vfOnmxpBGmnRqhrRLSDGyJa1tY0CgYEA30lEOZhrq6uJa8lFlWMR+MzVdIGC6JKo\n" +
            "5vJxINHfHUm0kqF+eySM4pm/XZaAr8JIDpZvKJKxnXc1BLoiH/lnfcYhkpS4weD2\n" +
            "NurbPm8Pagpqr+tVuTwu05KK0Q2/XLdKj/6NKabIN9ZF9MHjixG7iIcFpAo36rjO\n" +
            "Hsou7t0yxbsCgYBqF5dpVkubMb0Dv+cvu0bjTnaxdCFtJ/uk5lZG1fqv/AA0LTQG\n" +
            "I0TXBWxQzt/K2NdietxxH+d2o0/2yWdxndQJxHZBILnNUeML/e8OLXCFUpcefQgh\n" +
            "UCE7y48sDjbIoQY6h6RrGoeYGZeSQcRNY4B2Wl7o61W9Qu4XimIea21iSQKBgDmm\n" +
            "eBgK05nyYzvSLsYgWy6K7H31RnB4FWXzqOPZbCrqsdW+HqL6z+ld2vv19OnsVqB1\n" +
            "lOO75GIMukKrME5jHaZqtpZbEcz1IX0SbGMVV7yATgV31J1L/acgyfip/QOaS4Uc\n" +
            "KyRa7I0GJO/J888fV/UrL3ioLsHKz2VBvJZtxEMrAoGBAJEpHUxLry/mrV1scspr\n" +
            "p+oOCCQ7ozLhLXJ2i5xLrvx+lzdIdqi1PQZFWRZ4RzQomhY00POolQr+oieZw8Uf\n" +
            "fO8mCO3yj8TKJOAV1em/U0lOzsdVq2AkCYKQifyvRItgTYr6BjIUsWD0EInaYfK3\n" +
            "fMqmpnXyk70IoRGz7qcziZ82\n" +
            "-----END PRIVATE KEY-----\n";

    //商户证书编号
    private static final String PSN = "77E46A0289E0866B48D6E171B0E2DA42A576F265";

    //v3密钥
    private static final String V3Key = "b1e863e674bb4b5faf570d21a404ed7f";

    //小程序ID
    private static final String APPID = "wx4bf7b820ad506386";

    private static RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
            .merchantId(MID)
            .privateKey(PK)
            .merchantSerialNumber(PSN)
            .apiV3Key(V3Key)
            .build();

    private static NativePayService mNativePayService = new NativePayService.Builder()
            .config(config)
            .build();

    private static WxPayUtil instance;

    private WxPayUtil() {
    }

    public static synchronized WxPayUtil getInstance() {
        if (instance == null) {
            instance = new WxPayUtil();
        }
        return instance;
    }

    /**
     * 创建订单
     * @param tradeNo 订单号
     * @param noticeUrl 通知url
     * @param shopName 商品名称
     * @param price 金额
     * @return 支付url。空时异常
     */
    public String createOrder(String tradeNo, String noticeUrl, String shopName, int price) {
        try {
            PrepayRequest request = new PrepayRequest();
            Amount amount = new Amount();
            amount.setTotal(price * 100);
            request.setAmount(amount);
            request.setAppid(APPID);
            request.setMchid(MID);
            request.setDescription(shopName);
            request.setNotifyUrl(noticeUrl);
            request.setOutTradeNo(tradeNo);
            return mNativePayService.prepay(request).getCodeUrl();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 关闭订单
     */
    public void closeOrder(String tradeNo) {
        CloseOrderRequest closeRequest = new CloseOrderRequest();
        closeRequest.setMchid(MID);
        closeRequest.setOutTradeNo(tradeNo);
        mNativePayService.closeOrder(closeRequest);
    }

    /**
     * 支付回调验签
     * @param nonce HTTP 头 Wechatpay-Nonce
     * @param signature HTTP 头 Wechatpay-Signature
     * @param timestamp HTTP 头 Wechatpay-Timestamp
     * @param serial HTTP 头 Wechatpay-Serial
     * @param body HTTP 请求体 body
     * @return Transaction对象，返回空表示验签失败
     */
    public Transaction onPayResult(String nonce, String signature, String timestamp, String serial, String body) {
        // 构造 RequestParam
        try {
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(serial)
                    .nonce(nonce)
                    .signature(signature)
                    .timestamp(timestamp)
                    .body(body)
                    .build();
            return new NotificationParser(config).parse(requestParam, Transaction.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}